package org.NooLab.itexx.co;

import jlibs.core.lang.StringUtil;

import org.NooLab.itexx.ITexx;
import org.NooLab.itexx.comm.messages.MessageMap;
import org.NooLab.utilities.strings.StringsUtil;
import org.apache.commons.collections.BidiMap;


/**
 * 
 * since the msg is simple, we will use "MessageMap"
 * 
 * 
 *
 */
public class CoWorkerMsgDigest {

	ITexx itexx;
	CoWorker processDef ;
	CoWorkers coWorkers;
	
	public StringsUtil  strgutil = new StringsUtil();
	// ========================================================================
	public CoWorkerMsgDigest( ITexx itx, int srvPort, Object msgObj) {
		// 
		String secret="", name;
		int rPort=0;
		
		itexx = itx;
		
		coWorkers = itexx.getCoWorkersContainer() ;
		
		MessageMap mm = new MessageMap();
		
		mm.transportMsg( msgObj );
		
		BidiMap xc = mm.getxContent();
		if (xc.containsKey("process::secret")){
			secret = (String) mm.getxContent().get("process::secret") ;
		}
		 
		CoWorker p = coWorkers.getCoWorkerBySecret( secret );
		
		if (p!=null){
						itexx.out.print(3, "target for message has been identified:\n" +
								           "            secret : "+secret+"\n"+
								           "            name   : "+p.getName() +"\n");
			processDef = p;
			processDef.setStatus( CoWorkerIntf._CO_STATUS_CONFIRMED );
			// effectivePort <- responseport
			
			rPort = 0;
			if (xc.containsKey("process::responseport")){
				String str = (String) mm.getxContent().get("process::responseport") ;
				if (strgutil.isNumericX(str)){
					rPort = strgutil.getNumFromStr(str, 0);
				}
			}
			
			processDef.setEffectiveClientPort( srvPort, rPort );
			coWorkers.releaseFollowUp(p);
		}
		
	}
	// ........................................................................
	public CoWorkerMsgDigest( ITexx itx, CoWorker coWorker, 
							  int mainserverport, 
							  String msgStr) {
		
		String secret="", name;
		
		
		itexx = itx;
		
		coWorkers = itexx.getCoWorkersContainer() ;
		
		MessageMap mm = new MessageMap();
		
		mm.transportMsg( msgStr );
		
		BidiMap xc = mm.getxContent();
		if (xc.containsKey("process::secret")){
			secret = (String) mm.getxContent().get("process::secret") ;
		}
		 
		 
		CoWorker p = coWorkers.getCoWorkerBySecret( secret );
		
		if ((p!=null) && (secret.contentEquals(coWorker.getInstanceGuid()))){
			
			itexx.out.print(2,"message retrieved by iTexx through console...\n"+msgStr);
			
		}else{
			itexx.out.print(2,"untreated message in iTexx console...\n"+msgStr);
		}
		
		
	}

	// ========================================================================
	
	
	
}
